//流程图
function flowChart(peleId,data){
	jsPlumb.ready(function() {
		var instance = jsPlumb.getInstance({
			DragOptions : { cursor: 'pointer', zIndex:2000 },
			ConnectionOverlays : [
				[ "Arrow", { location:1 } ],
				[ "Label", { 
					location:0.1,
					id:"label",
					cssClass:"aLabel"
				}]
			],
			Container:peleId
		});

		// this is the paint style for the connecting lines..
		var connectorPaintStyle = {
			lineWidth:2,
			strokeStyle:"#61B7CF",
			joinstyle:"round",
			outlineColor:"white",
			outlineWidth:2
		},
		// .. and this is the hover style. 
		connectorHoverStyle = {
			lineWidth:4,
			strokeStyle:"#216477",
			outlineWidth:2,
			outlineColor:"white"
		},
		endpointHoverStyle = {
			fillStyle:"#216477",
			strokeStyle:"#216477"
		},
		// the definition of source endpoints (the small blue ones)
		sourceEndpoint = {
			endpoint:"Dot",
			paintStyle:{ 
				strokeStyle:"#7AB02C",
				fillStyle:"transparent",
				radius:7,
				lineWidth:3 
			},				
			isSource:true,
			connector:[ "Flowchart", { stub:[40, 60], gap:10, cornerRadius:5, alwaysRespectStubs:true } ],								                
			connectorStyle:connectorPaintStyle,
			hoverPaintStyle:endpointHoverStyle,
			connectorHoverStyle:connectorHoverStyle,
	        dragOptions:{},
	        overlays:[
	        	[ "Label", { 
	            	location:[0.5, 1.5], 
	            	label:"",
	            	cssClass:"endpointSourceLabel" 
	            } ]
	        ]
		},		
		// the definition of target endpoints (will appear when the user drags a connection) 
		targetEndpoint = {
			endpoint:"Dot",					
			paintStyle:{ fillStyle:"#7AB02C",radius:11 },
			hoverPaintStyle:endpointHoverStyle,
			maxConnections:-1,
			dropOptions:{ hoverClass:"hover", activeClass:"active" },
			isTarget:true,			
	        overlays:[
	        	[ "Label", { location:[0.5, -0.5], label:"", cssClass:"endpointTargetLabel" } ]
	        ]
		},			
		init = function(connection) {
			
			var targetEleId=connection.targetId;
			var sourceEleId=connection.sourceId;
			var sourceInfo=sourceEleId.split("_");
			var targetIdInfo=targetEleId.split("_");
			var currProcCode=sourceInfo[1];//获得当前流程码
			var targetProcCode=targetIdInfo[1];//获得目标流程码
			var tarResultCode="";
			if(!zfesUtil.isStrNull(targetProcCode)){
				if(targetIdInfo.length>2){
					tarResultCode=targetIdInfo[2];
				}
				for(var i=0;i<data.length;i++){
					if(zfesUtil.isStrNull(data[i].currentProcess)){
						continue;
					}
					var labelName=data[i].currentResultName;
					if(data[i].currentProcess==currProcCode&&data[i].targetProcess==targetProcCode&&labelName.indexOf("中")<0){
						if(!zfesUtil.isStrNull(data[i].targetResult)){
							if(data[i].targetResult==tarResultCode){
								connection.getOverlay("label").setLabel(data[i].currentResultName);
								break;
							}else{
								continue;
							}							
						}else{
							connection.getOverlay("label").setLabel(data[i].currentResultName);
							break;
						}
					}
				}
				jsPlumb.repaintEverything();
			}
			//connection.getOverlay("label").setLabel(connection.sourceId.substring(15) + "-" + connection.targetId.substring(15));
			connection.bind("editCompleted", function(o) {
				if (typeof console != "undefined")
					console.log("connection edited. path is now ", o.path);
			});
		};			

		var _addEndpoints = function(toId, sourceAnchors, targetAnchors) {
				for (var i = 0; i < sourceAnchors.length; i++) {
					var sourceUUID = "flowchart_"+toId +"_"+ sourceAnchors[i];
					instance.addEndpoint("flowchart_" + toId, sourceEndpoint, { anchor:sourceAnchors[i], uuid:sourceUUID });						
				}
				for (var j = 0; j < targetAnchors.length; j++) {
					var targetUUID = "flowchart_"+toId +"_"+ targetAnchors[j];
					instance.addEndpoint("flowchart_" + toId, targetEndpoint, { anchor:targetAnchors[j], uuid:targetUUID });						
				}
			};

		// suspend drawing and initialise.
		instance.doWhileSuspended(function() {
			//flowchart_"+data[i].currentProcess+"_"+data[i].currentResult+"
			var btnStyle="margin: 30px 50px 20px 20px;width: 100px;height: 50px;";
			//构建起点
			var btnStart="<button type='button' class='btn btn-lg flowBtn' id='flowchart_start' style='"+btnStyle+"'>起步</button>";
			$("#"+peleId).append(btnStart);
			var isAl="";
			var firstTargetId="";
			for(var i=0;i<data.length;i++){
				btnStyle="margin: 30px 80px 20px 80px;width: 150px;height: 50px;";
				if(zfesUtil.isStrNull(data[i].currentProcess)||zfesUtil.isStrNull(data[i].currentResult)){
					//创建连线
					var firstTargetId=data[i].targetProcess;
					continue;
				}
				var isFirst=data[i].isFirst;
				var isLast=data[i].isLast;
				var isAlWork=data[i].isAlWork;//是否已执行
				var className="btn btn-lg flowBtn ";
				var showName=data[i].currentProcessName;//显示名称
				var eleId=data[i].currentProcess;
				var nowId=data[i].currentProcess;
				
				if(!zfesUtil.isStrNull(isAlWork)&&isAlWork){
					className+=" btn-success ";
					//只要有，起步就一定执行
					$("#flowchart_start").addClass("btn-success");
				}
				if(!(isAl.indexOf(nowId)>=0)){//不是第二次创建的话构建按钮，链接点出点一个
					var tag="<button type='button' class='"+className+"' id='flowchart_"+eleId+"' style='"+btnStyle+"'>";
					tag+=showName+"</button>";
					$("#"+peleId).append(tag);
					//按钮创建完成，构建链接点
					_addEndpoints(eleId, ["RightMiddle"], ["LeftMiddle"]);
				}else{
					_addEndpoints(eleId, ["TopCenter"], []);//新增链接点
				}
				isAl+=nowId+",";//记录避免重复创建
				var targetId=data[i].targetProcess+"_"+data[i].targetResult;
				if(!zfesUtil.isStrNull(isLast)&&isLast){//如果是最后一步，再附加目标
					className+="btn-info ";
					btnStyle+="margin-top:100px;margin-left: 150px;";
					showName=data[i].targetResultName;//如果是最后一步，显示目标流程结果
					//eleId=data[i].targetProcess+"_"+data[i].targetResult;
					nowId=targetId;
					if((isAl.indexOf(nowId)>=0)){//第二次出现开始就不要了
						continue;
					}
					isAl+=nowId+",";//记录避免重复创建
					if(!zfesUtil.isStrNull(isAlWork)&&isAlWork){
						className+=" btn-success ";
					}
					tag="<button type='button' class='"+className+"' id='flowchart_"+targetId+"' style='"+btnStyle+"'>";
					tag+=showName+"</button><br/>";
					$("#"+peleId).append(tag);
					//创建结束链接点
					_addEndpoints(targetId,[],["LeftMiddle"]);
				}
			}
			_addEndpoints("start", ["RightMiddle"], []);
			// listen for new connections; initialise them the same way we initialise the connections at startup.
			instance.bind("connection", function(connInfo, originalEvent) { 
				init(connInfo.connection);
			});
			//创建连线
			var endTarId="";
			for(var i=0;i<data.length;i++){
				if(zfesUtil.isStrNull(data[i].currentProcess)||zfesUtil.isStrNull(data[i].currentResult)){
					continue;
				}
				var isFirst=data[i].isFirst;
				var isLast=data[i].isLast;
				var isAlWork=data[i].isAlWork;//是否已执行
				var currId=data[i].currentProcess;
				var targetId=data[i].targetProcess;
				if(!zfesUtil.isStrNull(isLast)&&isLast){//如果是最后一步，再附加目标
					targetId=data[i].targetProcess+"_"+data[i].targetResult;
					if(data[i].targetProcess==endTarId){
						instance.connect({uuids:["flowchart_"+currId+"_RightMiddle","flowchart_"+targetId+"_LeftMiddle" ], editable:false});
					}else{
						instance.connect({uuids:["flowchart_"+currId+"_TopCenter","flowchart_"+targetId+"_LeftMiddle" ], editable:false});
					}
				}else{
					instance.connect({uuids:["flowchart_"+currId+"_RightMiddle","flowchart_"+targetId+"_LeftMiddle" ], editable:false});
				}
				endTarId=data[i].targetProcess;
			}
			instance.connect({uuids:["flowchart_start_RightMiddle","flowchart_"+firstTargetId+"_LeftMiddle" ], editable:false});
		});

		jsPlumb.fire("jsPlumbDemoLoaded", instance);
		
	});
}
